package cn.jit.ssm.utils;

import com.alibaba.fastjson.JSON;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

/**
 * @author: Cecurio
 * @create: 2017-12-13 16:04
 **/
public class HttpClientUtil {
    private static CloseableHttpClient getCloseableHttpClient() {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        return httpClient;
    }

    /**
     *
     * @param url 要请求的Url,它返回的json数据
     * @param clazz 返回的json对象对应的实体类的class
     * @param <T>
     * @return 返回json对象对应实体类的对象
     */
    public static <T> T doGet(String url, Class<T> clazz) {
        T obj = null;
        CloseableHttpClient httpClient = getCloseableHttpClient();
        HttpGet httpGet = new HttpGet(url);
        RequestConfig requestConfig = RequestConfig.custom()
            .setConnectTimeout(1000).setConnectionRequestTimeout(1000)
            .setSocketTimeout(1000).setRedirectsEnabled(true).build();
        httpGet.setConfig(requestConfig);
        try {
            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity entity = httpResponse.getEntity();
            Header header = entity.getContentType();
            if (header != null && header.toString().contains("json")) {
                obj = clazz.newInstance();
                String content = EntityUtils.toString(entity);
                obj = JSON.parseObject(content, clazz);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return obj;
    }
}
